import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, DeviceEventEmitter, ScrollView,
	PixelRatio
} from 'react-native';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { LargeBtn } from '../../requirement-plan/component/Component.js';

const scale = GLOBAL.SCALE;
const optionPicSourse = require('../../../imgs/global/option.png');
const selectedPicSourse = require('../../../imgs/global/success.png');
export class BankArrayPage extends Component {

	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '银行信息',
			headerLeft: <Common type="headLeft" onPress={() => {
				navigation.navigate('EnterpriseCreateAdditionInfo', {
					bankList: navigation.state.params.bankList
				});
			}} />,
			headerRight: <TouchableOpacity onPress={() => {
				const { navigate } = navigation;
				navigate('BankAddPage', {
					goBack: 'BankArrayPage',
					companyAcct: {},
				});
			}} style={{ paddingRight: 12 * scale }}><Text style={styles.text}>添加</Text></TouchableOpacity>,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		};
	};

	constructor(props) {
		super(props);

		this.state = {
			bankList: [],
		}
		this._didPressLargeBtn = this._didPressLargeBtn.bind(this);
		this._setBank = this._setBank.bind(this);

	}

	componentWillMount () {
		this.props.navigation.setParams({
			bankList: this.state.bankList,
		})
	}

	componentDidMount () {
		const { bankList } = this.props.navigation.state.params;
		if (bankList && bankList.length) {
			this._setBank(bankList);
		}

		DeviceEventEmitter.addListener('bankParam', (res) => {
			const { bankList } = res;
			this._setBank(bankList);
		});

	}

	_setBank (bankes) {

		let { bankList } = this.state;
		if (bankes) {
			if (bankes.length == 1) {
				const companyAcct = bankes[0];
				if (typeof (companyAcct.index) != 'undefined') {
					bankList[companyAcct.index] = companyAcct;
				} else {
					if (bankList.length === 0) {
						companyAcct.index = 0;
					} else {
						companyAcct.index = bankList.length;
					}
					bankList.push(companyAcct);
				}
			} else {
				for (let i = 0; i < bankes.length; i++) {
					if (bankes[i]) {
						bankList[i] = bankes[i];
						bankList[i].index = i;
					}
				}
			}
		}

		let newArr = Array.from(new Set(bankList));
		this.setState({
			bankList: newArr,
		});

		this.props.navigation.state.params.bankList = bankList;
	}

	async _delItem (data) {
		const { bankList } = this.state;

		if (data.delType) {
			const params = {};
			params.companyAcct = data.companyAcct;
			params.bizType = 'COMPANY_ACCOUNT_INFO';
			const delResponse = await HTTP.POST(API_GENERATE(API.DELETE_COMPANY_INFO), params);
			if (delResponse) {
				bankList.splice(data.index, 1);
				console.log('del suc')
			} else {
				console.log('del fal')
			}
		} else {
			bankList.splice(data.index, 1);
		}

		this.setState({
			bankList
		})

		if (bankList.length < 1) {
			const { navigate } = this.props.navigation;
			const { responseData } = this.props.navigation.state.params;
			responseData.acctList = bankList;
			navigate('EnterpriseCreateAdditionInfo', {
				bankList,
				responseData
			});
		}
	}

	render () {
		let { bankList } = this.state;
		const bankView = bankList.map((companyAcct, index) => {
			if (companyAcct) {
				const { openBankName, openAcctNo, checked } = companyAcct;
				const source = checked ? selectedPicSourse : optionPicSourse;
				const defaultView = companyAcct.isDefault && companyAcct.isDefault === 1 ? <View style={styles.defaultCell}><Text style={styles.defaultText}>默认</Text></View> : <TouchableOpacity onPress={
					this._didDefaultBtn.bind(this, index)
				}><Text style={styles.defaultText}>设为默认</Text></TouchableOpacity>;
				return (
					<View style={styles.row} key={index}>
						<TouchableOpacity style={styles.rowMain} onPress={() => {
							const { bankList } = this.state;
							const bank = bankList[index];
							bank.checked = !bank.checked;
							bankList[index] = bank;
							this.setState({
								bankList
							});
						}}>
							<View style={styles.rowMainLeft}>
								<Image source={source} style={styles.circle} />
							</View>
							<TouchableOpacity style={styles.rowMainRight} onPress={() => {
								const { navigate } = this.props.navigation;
								companyAcct.index = index;
								navigate('BankAddPage', {
									goBack: 'BankArrayPage',
									companyAcct,
								});
							}}>
								<View style={styles.rowMainRow}><Text style={styles.text}>{openBankName}</Text></View>
								<View style={styles.rowMainRow}><Text style={styles.text}>{openAcctNo}</Text></View>
								<View style={styles.rowMainRow}>{defaultView}</View>
							</TouchableOpacity>
						</TouchableOpacity>
						<TouchableOpacity style={styles.rowSide} onPress={() => {
							/**
							 * delType 辨别是否已经提交到后台
							 * true 为已提交到后台，则删除时需要请求后台接口； false 未提交到后台 
							*/
							this._delItem({ companyAcct, delType: companyAcct.id ? true : false, index });
						}}>
							<Text style={[styles.text, { color: style.color.themeColor }]}>删除</Text>
						</TouchableOpacity>
					</View>
				)
			}
		})

		return (
			<View style={[styles.container]}>
				<ScrollView style={styles.scrollView} keyboardShouldPersistTaps={'handled'} keyboardDismissMode={'on-drag'}>

					<View style={styles.wrap}>
						<View style={{ width: 345 * scale, }}>{bankView}</View>
					</View>

				</ScrollView >
				<LargeBtn onPress={this._didPressLargeBtn} text={'确定'} />
			</View>

		)
	}

	/**
 * 点击底部按钮
 */
	_didPressLargeBtn () {
		const { navigate } = this.props.navigation;

		const { bankList } = this.state;

		navigate('EnterpriseCreateAdditionInfo', {
			bankList
		});

	}

	/**
	 * 点击设为默认按钮
	 */
	_didDefaultBtn (defalltIndex) {
		const { bankList } = this.state;
		bankList.map((companyAcct, index) => {
			companyAcct.isDefault = (defalltIndex == index) ? 1 : 2;  //1是默认，2不是默认
			this.setState({
				bankList,
			});
		})
	}

}

const styles = StyleSheet.create({
	defaultCell: {
		width: 50 * scale,
		height: 18 * scale,
		backgroundColor: '#F4F4F4',
		borderColor: '#F4F4F4',
		borderWidth: 1 / PixelRatio.get(),
		justifyContent: 'center',
		alignItems: 'center',
	},
	defaultText: {
		fontSize: 12 * scale,
		color: '#8B8B8B'
	},
	circle: {
		width: 14 * scale,
		height: 14 * scale,
	},
	row: {
		flexDirection: 'row',
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
	},
	rowSide: {
		width: 50 * scale,
		height: 70 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingTop: 15 * scale,
	},
	rowMain: {
		flex: 1,
		flexDirection: 'row',
	},
	rowMainLeft: {
		width: 25 * scale,
		height: 90 * scale,
		justifyContent: 'center',
	},
	rowMainRight: {
		flex: 1,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
	},
	rowMainRow: {
		flex: 1,
		flexDirection: 'row',
		// justifyContent: 'space-between',
		alignItems: 'center',
	},
	text: {
		fontSize: 14 * scale,
		color: '#4B4B4B'
	},
	scrollView: {
		flex: 1,

	},
	container: {
		flex: 1,
		backgroundColor: '#F5F5F5',
	},
	wrap: {
		backgroundColor: '#fff',
		alignItems: 'center',
	},
})